/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package sudoku;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

/**
 *
 * @author Roy
 */
public class Sudoku extends JPanel {

	private Square[][] squares;
	private Link[] rows;
	private Link[] columns;
	private Link[][] blocks;

	private void initialLinks() {
		rows = new Link[9];
		columns = new Link[9];
		blocks = new Link[3][3];
		for(int i = 0; i < 9; i++) {
			rows[i] = new Link(9);
			columns[i] = new Link(9);
			blocks[i / 3][i % 3] = new Link(9);
		}
	}

	private void initialSquares() {
		squares = new Square[9][9];
		for (int i = 0; i < 9; i++) {
			for (int j = 0; j < 9; j++) {
				squares[i][j] = new Square(9);
				rows[i].add(squares[i][j]);
				columns[j].add(squares[i][j]);
				blocks[i / 3][j / 3].add(squares[i][j]);
			}
		}
	}

	private void showSquares() {
		setLayout(new GridLayout(9,9));
		for (int i = 0; i < 9; i++) {
			for (int j = 0; j < 9; j++) {
				add(squares[i][j]);
			}
		}
	}
	
	public Sudoku() {
		initialLinks();
		initialSquares();
		showSquares();
	}

	public void solve() {
		boolean b = true;
		while(b) {
			b = false;
			for(int i = 0; i < 9; i++) {
				b = b | rows[i].update();
				b = b | columns[i].update();
				b = b | blocks[i / 3][i % 3].update();
			}
			for(int i = 0; i < 9; i++) {
				b = b | rows[i].scan();
				b = b | columns[i].scan();
				b = b | blocks[i / 3][i % 3].scan();
			}
		}
	}

	public boolean IsSolved() {
		for(int i = 0; i < 9; i++) {
			for(int j = 0; j < 9; j++) {
				if(squares[i][j].get() == 0) {
					return false;
				}
			}
		}
		return true;
	}
}
